//ENCRIPTION.v - This is the encription hardware for project 2.
//
// Created By:	Jesse Inkpen
// Date:	18-February-2014
//
// This module has a three fixed values applied to its input port and waits
// untill a go signal to start calculating an RSA encription block
// Use the define 'BITS to set the bit size of the ENCRIPTION.v synthesis.
///////////////////////////////////////////////////////////////////////////

`define BITS 16

module RSA(
	input						clk,		// clock
	input						go,		// hardware go go go
	input	[`BITS-1:0]		m,		// message
	input	[`BITS-1:0]		e,		// exponent
	input	[`BITS-1:0]		n,		// modulous
			
	output	reg [`BITS-1:0] r,		// post processing result
	output	reg			d				// done signal
	);

	reg 	[`BITS*2-1:0]		z;			// message register
	reg 	[`BITS*2-1:0]		p;			// 
	reg	[`BITS-1:0]			exp;		// exponent
	
	always @(posedge clk) 
	begin	
		if (~go) 
		begin	
			z <= 1;
			p <= m;
			d <= 0;
			exp <= e;
		end
		else if(exp != 0)
		begin
			p	<= ((p * p) % n);
			if(exp[0] == 1)
				z	<=	((z * p) % n);
			else
				z <= z;
			exp <= (exp >> 1);	
		end
		else
		begin
			d	<= 1;
			r	<=	z[`BITS-1:0];	
		end
	end
endmodule
				